package com.bawei.demo_shoppingcar.fragment;


import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bawei.demo_shoppingcar.R;
import com.bawei.demo_shoppingcar.activity.AD5WebViewActivity;
import com.bawei.demo_shoppingcar.activity.CommodityActivity;
import com.bawei.demo_shoppingcar.adapter.AdvertisePagerViewAdapter;
import com.bawei.demo_shoppingcar.adapter.ShoppingAdapter;
import com.bawei.demo_shoppingcar.application.ContentData;
import com.bawei.demo_shoppingcar.bean.CommdityBean;
import com.bawei.demo_shoppingcar.bean.ShoppingDataBean;
import com.bawei.demo_shoppingcar.interfac.UpdateShopping;
import com.bawei.demo_shoppingcar.utils.HomeAsyncTask;
import com.bawei.demo_shoppingcar.utils.NetworkMessage;
import com.bawei.demo_shoppingcar.widget.WrapAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private List<ShoppingDataBean.DataBean.Ad5Bean> ad5;
    private ShoppingDataBean.DataBean data;
    private String mParam1;
    private String mParam2;
    private RecyclerView recyclerView;
    private RelativeLayout headerLayout;
    private LinearLayout mDotLayout;
    // 广告轮播
    private ViewPager mAdverViewpager;
//    //广告集合-----------------
    private List<Map<String, Object>> listHader = new ArrayList<Map<String, Object>>();
    private AdvertisePagerViewAdapter mAdvertiseAdapter;
    private ShoppingAdapter mShoppingAdapter;
    private WrapAdapter<ShoppingAdapter> mWrapAdapter;
    private SwipeRefreshLayout mSwipeRefreshWidget;
    private List<View> listDot = new ArrayList<>();

    ShoppingDataBean homeObject;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int type = msg.what;
            if (type == 1) {
                int currentItem = mAdverViewpager.getCurrentItem();
                mAdverViewpager.setCurrentItem(++currentItem);
                mHandler.sendEmptyMessageDelayed(1, 1500);
            } else if (type == 2) {
                mShoppingAdapter.notifyDataSetChanged();
                mAdvertiseAdapter.notifyDataSetChanged();
                mSwipeRefreshWidget.setRefreshing(false);
            }
        }
    };

    public HomeFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View inflate = inflater.inflate(R.layout.fragment_home, container, false);
        initView(inflate);
        initData();
        setDot();
        setAdapter();
        AdvertiseMonitor();

        return inflate;
    }

    //开启线程获得网络数据
    private void getAsyncTaskData() {

        List<ShoppingDataBean.DataBean.Ad1Bean> ad1 = homeObject.getData().getAd1();

        for (int i = 0; i < ad1.size(); i++) {
            Map<String, Object> mapImageURL = new HashMap<>();
            String image = ad1.get(i).getImage();
            mapImageURL.put("url", image);
            mapImageURL.put("view", new ImageView(getContext()));
            listHader.add(mapImageURL);
        }

        data = homeObject.getData();

        mShoppingAdapter = new ShoppingAdapter(getContext(), data);
        mWrapAdapter = new WrapAdapter<>(mShoppingAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));

        // 设置头部占据一行
        mWrapAdapter.adjustSpanSize(recyclerView);
        // 设置RecyclerView的数据适配器(适配器包装)
        recyclerView.setAdapter(mWrapAdapter);
        // 添加头布局
        mWrapAdapter.addHeaderView(headerLayout);
        //默认
        mAdverViewpager.setCurrentItem(Integer.MAX_VALUE / 2 - ((Integer.MAX_VALUE / 2) % 9));
        ad5 = data.getAd5();

    }

    //viewPager监听
    private void AdvertiseMonitor() {
        mAdverViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                dynaSetDot(position % 9);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
    //动态设置viewPager小圆点
    private void dynaSetDot(int index) {
        for (int i = 0; i < listDot.size(); i++) {
            if (index == i) {
                listDot.get(i).setBackgroundResource(R.drawable.point_selected);
            } else {
                listDot.get(i).setBackgroundResource(R.drawable.point_normal);
            }
        }
    }
    //加载数据
    private void initData() {

        HomeAsyncTask asyncTask = new HomeAsyncTask(getContext(), new UpdateShopping() {
/*

            private List<ShoppingDataBean.DataBean.Ad5Bean> ad5;
            private ShoppingDataBean.DataBean data;
*/

            @Override
            public void getHaderImageURL(ShoppingDataBean dataBean) {

                homeObject = dataBean;
                getAsyncTaskData();
                //recyclerView下拉刷新监听事件
                mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        mSwipeRefreshWidget.setRefreshing(true);
                        mHandler.sendEmptyMessageDelayed(2, 2000);
                    }
                });
                //recyclerView条目监听事件
                mShoppingAdapter.setImageLayoutItemClickListener(new ShoppingAdapter.MyImageLayoutItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        String url = ad5.get(position - 1).getUrl();
                        Intent intent = new Intent(getActivity(), AD5WebViewActivity.class);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    }
                });
                //recyclerView条目监听事件
                mShoppingAdapter.setDefaultItemClickListener(new ShoppingAdapter.MyDefaultItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        position = position - ad5.size() - 1;

                        List<ShoppingDataBean.DataBean.DefaultGoodsListBean> defaultGoodsList = data.getDefaultGoodsList();
                        ShoppingDataBean.DataBean.DefaultGoodsListBean defaultGoodsListBean = defaultGoodsList.get(position);
                        String goods_img = defaultGoodsListBean.getGoods_img();
                        String goods_name = defaultGoodsListBean.getGoods_name();
                        double shop_price = defaultGoodsListBean.getShop_price();
                        CommdityBean commdityBean = new CommdityBean(goods_img, goods_name, shop_price);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", commdityBean);
                        Intent intent = new Intent(getActivity(), CommodityActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });
            }
        });

        //判断网络状态
        boolean networkAvailable = NetworkMessage.isNetworkAvailable(getContext());
        if (networkAvailable) {
            asyncTask.execute(ContentData.url);
        } else {
            //dialog网络设置
            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
            dialog.setTitle("请选择");
            dialog.setMessage("是否立即设置网络?");
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //进入网络设置界面
                    setNetwork(getContext());
                }
            });
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            dialog.show();
        }
    }

    //设置适配器
    private void setAdapter() {
        /**
         * viewpager适配器
         */
        mAdvertiseAdapter = new AdvertisePagerViewAdapter(listHader);
        mAdverViewpager.setAdapter(mAdvertiseAdapter);
        mHandler.sendEmptyMessageDelayed(1, 1500);
        // 设置布局显示方式，这里我使用都是垂直方式——LinearLayoutManager.VERTICAL
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayout.VERTICAL, false));
        // 设置添加删除item的时候的动画效果
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    //initView
    private void initView(View inflate) {
        recyclerView = (RecyclerView) inflate.findViewById(R.id.recyclerView);
        headerLayout = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.recyclerview_header, null);
        //头部控件初始化
        mAdverViewpager = (ViewPager) headerLayout.findViewById(R.id.ad_viewpager);//初始化广告轮播ViewPager
        mDotLayout = (LinearLayout) headerLayout.findViewById(R.id.dot_layout);//广告对应的dot
        mSwipeRefreshWidget = (SwipeRefreshLayout) inflate.findViewById(R.id.swipeRefresh);//recyclerView刷新控件
    }

    //初始化小圆点
    private void setDot() {
        // 多少个轮播广告就多少个点dot
        for (int i = 0; i < 9; i++) {
            View view = new View(getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(8, 8);
            if (i != 0) {//第一个点不需要左边距
                params.leftMargin = 5;
            }
            view.setLayoutParams(params);
            if (i == 0) {
                view.setBackgroundResource(R.drawable.point_selected);
            } else {
                view.setBackgroundResource(R.drawable.point_normal);
            }
            mDotLayout.addView(view);
            listDot.add(view);
        }
    }

    private void setNetwork(Context context) {
        Intent intent = null;
        //判断手机系统的版本  即API大于10 就是3.0或以上版本
        if (android.os.Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        } else {
            intent = new Intent();
            ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
            intent.setComponent(component);
            intent.setAction("android.intent.action.VIEW");
        }
        context.startActivity(intent);
    }
}
